package com.zj.leetcode.medium.listNode;

/**
 * @program: algorithm
 * @description: 反转链表 II
 * 92 reverse-linked-list-ii
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class ReverseLinkedListIi {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5, null)))));

        ListNode head = new ListNode(5, null);
        Solution solution = new ReverseLinkedListIi().new Solution();
        System.out.println(solution.reverseBetween(listNode, 3, 4));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    class Solution {
        public ListNode reverseBetween(ListNode head, int left, int right) {

            if (head == null || head.next == null || left == right) {
                return head;
            }
            int i = 1;
            int flag = i;

            ListNode cur = head;
            ListNode leftN = null;
            ListNode front = head;

            while (cur.next != null) {
                if (i + 1 == left) {
                    leftN = cur;
                    front = cur.next;
                    flag = i + 1;
                }
                if (i >= left && i < right) {
                    ListNode next = cur.next;
                    cur.next = cur.next.next;
                    next.next = front;
                    front = next;

                    if (leftN != null) {
                        leftN.next = front;
                    }
                } else {
                    cur = cur.next;
                }

                ++i;
                if (i >= right) {
                    return flag != 1 ? head : front;
                }
            }

            return flag != 1 ? head : front;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}